package com.iweb.dao;


import com.iweb.pojo.Travel;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class TravelDaoImpl implements TravelDao{

    private Connection connection;
    private PreparedStatement pst;
    private ResultSet rs;

    public TravelDaoImpl(Connection connection) {
        this.connection = connection;
    }

    @Override
    public List<Travel> findAll() throws Exception {
        List<Travel> travels = new ArrayList<>();
        String sql = "select * from tb_travel ";

        //预编译
        pst = connection.prepareStatement(sql);

        rs = pst.executeQuery();
        Travel travel = null;
        while (rs.next()){
            travel = createTravel(rs);
            travels.add(travel);
        }

        return travels;

    }

    @Override
    public List<Travel> selectSite(String title) throws Exception {

        List<Travel> travels = new ArrayList<>();
        String sql = "select * from tb_travel ";
        //查询条件
        if(title!=null){
            sql += "where travel_title like ?";
        }
        //预编译
        pst = connection.prepareStatement(sql);

        if (title != null) {
            pst.setObject(1,"%"+title+"%");
        }
        //存放数据库信息
        rs = pst.executeQuery();

        Travel travel = null;
        while (rs.next()){
            travel = createTravel(rs);
            travels.add(travel);
        }

        return travels;
    }

    @Override
    public Travel findById(String id) throws Exception {
        Travel travel = null;
        String sql = "select * from tb_travel where travel_id= ?";

        //预编译
        pst = connection.prepareStatement(sql);
        pst.setObject(1,id);

        rs = pst.executeQuery();

        while(rs.next()){
            travel = createTravel(rs);
        }
        return travel;
    }


    private Travel createTravel(ResultSet rs) throws Exception{
        Travel travel = new Travel();
        travel.setId(rs.getString(1));
        travel.setTitle(rs.getString(2));
        travel.setPrice(rs.getDouble(3));
        travel.setTitleImg(rs.getString(4));
        travel.setDetail(rs.getString(5));
        travel.setDetailImg(rs.getString(6));
        travel.setBuyPoint(rs.getString(7));
        return travel;
    }
}
